<template>
  <div class="main-box">
    <OrganizeTree label="deptName" :data="treeFilterData" @change="changeTreeFilter">
    </OrganizeTree>
    <div class="table-box">
      <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam" :search-col="5"
        :data-callback="dataCallback" data-key="userPageListVoList">
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <SButton :buttonProps="{ type: 'primary' }" buttonText="新增" contentType="both" icon="CirclePlus"
            @click="openDialog('新增')" />
          <!-- <SButton :buttonProps="{ type: 'primary' }" buttonText="导入" contentType="both" icon="Upload"
            @click="importUserInfo" />
          <SButton :buttonProps="{ type: 'primary' }" buttonText="导出" contentType="both" icon="Download"
            @click="exportUserInfo" /> -->
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="编辑"
            @click="openDialog('编辑', scope.row)" />
          <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="离职" @click="handleLeave(scope.row)" />
          <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="重置密码" @click="resetPass(scope.row)" />
          <el-popconfirm title="确认禁用吗?" @confirm="(e: any) => handleDisable(scope.row, e)">
            <template #reference>
              <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="禁用" />
            </template>
          </el-popconfirm>

          <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="详情"
            @click="openDialog('详情', scope.row)" />
        </template>
      </ProTable>


      <UserDialog ref="userDialogRef" :title="dialogTitle" :rowData="selectedRow" v-model:visible="dialogVisible"
        @refresh="proTable?.getTableList" />

      <!-- 导入弹窗 -->
      <ImportDialog ref="importUserInfoRef" v-model="importUserInfoVisible" :dialogVisible="importUserInfoVisible"
        :template-name="templateName" :template-url="templateUrl" :upload-action="uploadAction" @ok="handleImportOk"
        @close="importUserInfoVisible = false" />

      <!-- 导出弹窗 -->
      <ExportDialog ref="exportUserInfoRef" v-model="exportUserInfoVisible" :dialogVisible="exportUserInfoVisible"
        :templateName="templateName" :selectedItems="selectedItems" :columns="cities"
        @close="exportUserInfoVisible = false" @ok="handleExportOk" />

      <LeaveDialog ref="leaveDialogRef" v-model="leaveVisible" :dialogVisible="leaveVisible" :rowId="rowId"
        :title="leaveTitle" @close="leaveVisible = false" @confirm="handleLeaveOk" />
    </div>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { User } from "@/api/interface";
import { useHandleData, useHandleOperation } from "@/hooks/useHandleData";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import ProTable from "@/components/ProTable/index.vue";
import UserDialog from "./modules/UserDialog.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { getUserList, editUser, addUser, userResetPassword, userDisable } from "@/api/basic/user";
import SButton from "@/components/SButton/index.vue";
import ImportDialog from "@/components/ImportExport/ImportDialog.vue";
import ExportDialog from '@/components/ImportExport/ExportDialog.vue';
import LeaveDialog from "./modules/LeaveDialog.vue";
import { dayjs, ElMessage, ElMessageBox } from "element-plus";
import { useDataStore } from '@/stores/modules/data'
import { userStatus } from "@/utils/dict";
import OrganizeTree from "./modules/OrganizeTree.vue"
import { getOrganicTree } from "@/api/modules/organize";

const dataStore = useDataStore()

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const res = await getOrganicTree();
  treeFilterData.value = res;
};

onMounted(() => {
  getTreeFilter();
});
// 树形筛选切换
const changeTreeFilter = (val: string) => {
  initParam.deptName = val
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive<any>({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data._embedded.userListPaginationQueryInformationDTOList,
    total: data.page.totalElements
  };
};


// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getUserList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();
onMounted(async () => {
  await dataStore.fetchRoleList();
  await dataStore.fetchDepartmentList()
});

// const roleList = computed(() => dataStore.roleList);
// const departmentList = computed(() => dataStore.departmentList);


// 表格配置项
const columns = reactive<any[]>([
  { type: "selection", fixed: "left", width: 70 },
  {
    prop: "username",
    label: "用户姓名",
    search: { el: "input" }
  },
  {
    prop: "sexName",
    label: "性别",
  },
  {
    prop: "loginName",
    label: "登录账号",
    search: { el: "input" },
  },
  {
    prop: "deptName", label: "部门",
    // search: { el: "tree-select", props: { filterable: true }, key: "deptName" },
    // isFilterEnum: false,
    // enum: departmentList,
    // fieldNames: { label: "deptName", value: "deptName" },
  },
  {
    prop: "jobName",
    label: "职位",
    search: { el: "input" },
  },
  {
    prop: "status",
    label: "状态",
    search: { el: "select" },
    enum: userStatus,
  },
  {
    prop: "phoneNumber",
    label: "手机号码",
    search: { el: "input" }
  },
  {
    prop: "createTime",
    label: "创建时间",
    render: ({ row }) => dayjs(row.createTime * 1000).format("YYYY-MM-DD HH:mm:ss"),
    width: 200
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

//禁用
const handleDisable = (row: any, e: any) => {
  userDisable(row.id).then(() => {
    ElMessage.success({ message: '禁用成功' });
    proTable.value?.getTableList();
  }).catch((err) => {
    ElMessage.error({ message: '禁用失败' });
  })
}

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  await useHandleOperation(userResetPassword, { id: params.id, newPassword: 'zs123456' }, params.username);
  proTable.value?.getTableList();
};

// 打开 dialog(新增、查看、编辑)
const dialogTitle = ref('');
const dialogVisible = ref(false);
const selectedRow = ref<Partial<User.ResUserList>>({});
const userDialogRef = ref<InstanceType<typeof UserDialog> | null>(null);

const openDialog = (title: string, row: Partial<User.ResUserList> = {}) => {
  dialogTitle.value = title;
  selectedRow.value = row;
  dialogVisible.value = true;
  userDialogRef.value?.acceptParams({
    title,
    isView: title === '详情',
    row,
    api: title === '新增' ? addUser : editUser,
    getTableList: proTable.value?.getTableList
  });
};

//导入
const importUserInfoRef = ref<InstanceType<typeof ImportDialog> | null>(null);
const importUserInfoVisible = ref(false);
const templateName = '用户信息';
const templateUrl = '/path/to/template.xlsx';
const uploadAction = 'https://jsonplaceholder.typicode.com/posts/';
const importUserInfo = async () => {
  importUserInfoVisible.value = true;
};
const handleImportOk = async () => {
  importUserInfoVisible.value = false;
  proTable.value?.getTableList();
}

//导出
const exportUserInfoRef = ref<InstanceType<typeof ExportDialog> | null>(null);
const exportUserInfoVisible = ref(false);
const selectedItems = [];

const cities = ['序号', '姓名', '性别', '年龄', '账号', '密码', '所属部门', '创建时间', '密码', '创建人', '身份证号码'];

const exportUserInfo = async () => {
  exportUserInfoVisible.value = true;
};

const handleExportOk = async () => {
  exportUserInfoVisible.value = false;
};

//离职
const leaveVisible = ref(false);
const rowId = ref<any>()
const leaveTitle = ref('')
const handleLeave = (row: User.ResUserList) => {
  rowId.value = Number(row.id)
  leaveTitle.value = `离职：${row.username}`
  leaveVisible.value = true;
};

const handleLeaveOk = async () => {
  leaveVisible.value = false;
  proTable.value?.getTableList();
}
</script>
